package le.cn.bio.server;

import cn.le.util.info.HostInfo;
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOEchoServer implements Runnable{

    public static void main(String[] args) throws IOException {
        ServerSocket socket = new ServerSocket(HostInfo.PORT);
        System.out.println("服务端启动成功,监听"+HostInfo.PORT+"端口");
        boolean flag = true;
        ExecutorService executors = Executors.newFixedThreadPool(10);
        while (flag){
            Socket client = socket.accept();
            //executors.submit(new EchoClientHandler(client));
            Thread thread = new Thread(new EchoClientHandler(client));
            thread.start();
        }
        executors.shutdown();
        socket.close();
    }

    private static class EchoClientHandler implements Runnable{
        private Socket client;//每个客户端都需要启动一个任务(task)来执行
        private Scanner scanner;
        private PrintStream out;
        private boolean flag = true;
        public EchoClientHandler(Socket client){
            this.client = client;
            try {
                this.scanner = new Scanner(this.client.getInputStream());
                this.scanner.useDelimiter("\n");//设置换行符
                this.out = new PrintStream(this.client.getOutputStream());
            }catch (IOException e){
                e.fillInStackTrace();
            }
        }

        public void run() {
            while (this.flag){
                if (this.scanner.hasNext()){//等待数据输入
                    String val = this.scanner.next().trim();
                    if ("bytbyt".equalsIgnoreCase(val)){
                        this.out.print("bytbytbyt...");
                        this.flag = false;
                    }else {
                        out.println("[echo] "+ val);
                    }
                }
            }
        }
    }

    public void run() {

    }
}
